package com.lwf.fatapi.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.StrUtil;
import com.lwf.fatapi.dto.CreateUserRequest;
import com.lwf.fatapi.entities.SysUser;
import com.lwf.fatapi.entities.SysUserRole;
import com.lwf.fatapi.exception.BusinessException;
import com.lwf.fatapi.mapper.SysUserMapper;
import com.lwf.fatapi.mapper.SysUserRoleMapper;
import com.lwf.fatapi.service.SysUserService;
import com.lwf.fatapi.utils.PasswordUtils;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

import static com.lwf.fatapi.entity.table.SysUserTableDef.SYS_USER;

/**
 * 系统用户服务实现类
 *
 * @author lwf
 */
@Service
public class SysUserServiceImpl implements SysUserService {

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean createUser(CreateUserRequest request) {
        // 检查用户名是否已存在
        SysUser existUser = userMapper.selectByUsername(request.getUsername());
        if (existUser != null) {
            throw new BusinessException("用户名已存在");
        }

        // 检查邮箱是否已存在
        if (StrUtil.isNotBlank(request.getEmail())) {
            SysUser existEmailUser = userMapper.selectByEmail(request.getEmail());
            if (existEmailUser != null) {
                throw new BusinessException("邮箱已存在");
            }
        }

        // 检查手机号是否已存在
        if (StrUtil.isNotBlank(request.getPhone())) {
            SysUser existPhoneUser = userMapper.selectByPhone(request.getPhone());
            if (existPhoneUser != null) {
                throw new BusinessException("手机号已存在");
            }
        }

        // 创建用户
        SysUser user = SysUser.builder()
                .username(request.getUsername())
                .password(PasswordUtils.encode(request.getPassword()))
                .nickname(request.getNickname())
                .email(request.getEmail())
                .phone(request.getPhone())
                .avatar(request.getAvatar())
                .status(request.getStatus() != null ? request.getStatus() : 1)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .createBy(getCurrentUserId())
                .isDeleted(0)
                .build();

        boolean result = userMapper.insert(user) > 0;

        // 设置用户角色
        if (result && request.getRoleIds() != null && !request.getRoleIds().isEmpty()) {
            setUserRoles(user.getId(), request.getRoleIds());
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(Long id, CreateUserRequest request) {
        SysUser existUser = userMapper.selectOneById(id);
        if (existUser == null) {
            throw new BusinessException("用户不存在");
        }

        // 检查用户名是否已被其他用户使用
        SysUser usernameUser = userMapper.selectByUsername(request.getUsername());
        if (usernameUser != null && !usernameUser.getId().equals(id)) {
            throw new BusinessException("用户名已存在");
        }

        // 检查邮箱是否已被其他用户使用
        if (StrUtil.isNotBlank(request.getEmail())) {
            SysUser emailUser = userMapper.selectByEmail(request.getEmail());
            if (emailUser != null && !emailUser.getId().equals(id)) {
                throw new BusinessException("邮箱已存在");
            }
        }

        // 检查手机号是否已被其他用户使用
        if (StrUtil.isNotBlank(request.getPhone())) {
            SysUser phoneUser = userMapper.selectByPhone(request.getPhone());
            if (phoneUser != null && !phoneUser.getId().equals(id)) {
                throw new BusinessException("手机号已存在");
            }
        }

        // 更新用户信息
        existUser.setUsername(request.getUsername());
        if (StrUtil.isNotBlank(request.getPassword())) {
            existUser.setPassword(PasswordUtils.encode(request.getPassword()));
        }
        existUser.setNickname(request.getNickname());
        existUser.setEmail(request.getEmail());
        existUser.setPhone(request.getPhone());
        existUser.setAvatar(request.getAvatar());
        if (request.getStatus() != null) {
            existUser.setStatus(request.getStatus());
        }
        existUser.setUpdateTime(LocalDateTime.now());
        existUser.setUpdateBy(getCurrentUserId());

        boolean result = userMapper.update(existUser) > 0;

        // 更新用户角色
        if (result && request.getRoleIds() != null) {
            setUserRoles(id, request.getRoleIds());
        }

        return result;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteUser(Long id) {
        SysUser user = userMapper.selectOneById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        // 逻辑删除用户
        user.setIsDeleted(1);
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(getCurrentUserId());

        boolean result = userMapper.update(user) > 0;

        // 删除用户角色关联
        if (result) {
            userRoleMapper.deleteByUserId(id);
        }

        return result;
    }

    @Override
    public SysUser getUserById(Long id) {
        return userMapper.selectOneByQuery(
                QueryWrapper.create().where(SYS_USER.ID.eq(id).and(SYS_USER.IS_DELETED.eq(0)))
        );
    }

    @Override
    public SysUser getUserByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    @Override
    public Page<SysUser> getUserPage(int pageNo, int pageSize, String keyword) {
        QueryWrapper query = QueryWrapper.create()
                .where(SYS_USER.IS_DELETED.eq(0));

        if (StrUtil.isNotBlank(keyword)) {
            query.and(SYS_USER.USERNAME.like(keyword)
                    .or(SYS_USER.NICKNAME.like(keyword))
                    .or(SYS_USER.EMAIL.like(keyword))
                    .or(SYS_USER.PHONE.like(keyword)));
        }

        query.orderBy(SYS_USER.CREATE_TIME.desc());

        return userMapper.paginate(pageNo, pageSize, query);
    }

    @Override
    public List<SysUser> getAllUsers() {
        return userMapper.selectListByQuery(
                QueryWrapper.create().where(SYS_USER.IS_DELETED.eq(0))
                        .orderBy(SYS_USER.CREATE_TIME.desc())
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean setUserRoles(Long userId, List<Long> roleIds) {
        // 删除原有角色
        userRoleMapper.deleteByUserId(userId);

        // 添加新角色
        if (roleIds != null && !roleIds.isEmpty()) {
            for (Long roleId : roleIds) {
                SysUserRole userRole = SysUserRole.builder()
                        .userId(userId)
                        .roleId(roleId)
                        .createTime(LocalDateTime.now())
                        .createBy(getCurrentUserId())
                        .build();
                userRoleMapper.insert(userRole);
            }
        }

        return true;
    }

    @Override
    public boolean resetPassword(Long id, String newPassword) {
        SysUser user = userMapper.selectOneById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        user.setPassword(PasswordUtils.encode(newPassword));
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(getCurrentUserId());

        return userMapper.update(user) > 0;
    }

    @Override
    public boolean changePassword(Long id, String oldPassword, String newPassword) {
        SysUser user = userMapper.selectOneById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        if (!PasswordUtils.matches(oldPassword, user.getPassword())) {
            throw new BusinessException("原密码错误");
        }

        user.setPassword(PasswordUtils.encode(newPassword));
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(getCurrentUserId());

        return userMapper.update(user) > 0;
    }

    @Override
    public boolean toggleUserStatus(Long id, Integer status) {
        SysUser user = userMapper.selectOneById(id);
        if (user == null) {
            throw new BusinessException("用户不存在");
        }

        user.setStatus(status);
        user.setUpdateTime(LocalDateTime.now());
        user.setUpdateBy(getCurrentUserId());

        return userMapper.update(user) > 0;
    }

    /**
     * 获取当前登录用户ID
     */
    private Long getCurrentUserId() {
        try {
            return Long.valueOf(StpUtil.getLoginId().toString());
        } catch (Exception e) {
            return null;
        }
    }
}
